package com.example.rxpermissiondemo;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;

/**
 * @author josan_tang
 * @date 11/27/17.
 */

public class PermissionUtil {
    private static final String TAG = "PermissionUtil";
    private RxPermissions rxPermissions;
    List<String> nextNeedRequestPermissions;
    List<String> noLongerRemindPermissions;
    /**
     * 一开始就需要赋予的权限
     */
    public static String[] REQUEST_PRIMISSION = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE};

    private PermissionUtil() {
    }

    private static class SingletonHolder {
        private static final PermissionUtil INSTANCE = new PermissionUtil();
    }
    
    public static PermissionUtil getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 申请权限
     * @param activity
     * @param callBackLisenter
     * @param permission
     */
    public void requestPermission(final Activity activity, final CallBackLisenter callBackLisenter, final String permission) {
        if (permission == null) {
            return;
        }
        rxPermissions = new RxPermissions(activity);
        if (rxPermissions.isGranted(permission)) {
            if (callBackLisenter != null) {
                callBackLisenter.granted();
            }
            return;
        }
        rxPermissions.requestEach(permission)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (callBackLisenter != null) {
                            if (permission.granted) {
                                callBackLisenter.granted();
                            } else {
                                if (permission.shouldShowRequestPermissionRationale) {
                                    callBackLisenter.refused();
                                } else {
                                    callBackLisenter.noLongerRemind();
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 必须要被授予的权限
     * @param activity
     * @param permissions
     */
    public void mustBeGranted(final Activity activity, String... permissions) {
        rxPermissions = new RxPermissions(activity);
        requestPermission(activity, new PermissionUtil.CallBackLisenter() {
            @Override
            public void granted() {
                Log.e(TAG, "call: 全部授予了权限，可以做其他的事情了！");
            }

            @Override
            public void refused() {
                Log.e(TAG, "refused: ");
            }

            @Override
            public void noLongerRemind(String... permissionNames) {
                String content = "如下权限需要授予，";
                for (String permissionName : permissionNames) {
                    content += permissionName + "\n";
                }
                content += "请到设置中去授予！";
                DialogUtil.showGoSettingDialog(activity, content);
            }
        }, permissions);
    }


    private void requestPermission(final Activity activity, final CallBackLisenter callBackLisenter, final String... permissions) {
        nextNeedRequestPermissions = new ArrayList();
        noLongerRemindPermissions = new ArrayList<>();
        rxPermissions.requestEach(permissions)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            Log.e(TAG, "accept: 授予了权限");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            Log.e(TAG, "accept: 拒绝了权限， 没有点击不要提醒，弹框解释为什么需要权限");
                            nextNeedRequestPermissions.add(permission.name);
                        } else {
                            Log.e(TAG, "accept: 拒绝了权限，点击了不要再提醒，跳转设置页面");
                            noLongerRemindPermissions.add(permission.name);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        // noLongerRemindPermissions的判断一定要放在nextNeedRequestPermissions之前
                        // 因为有多个权限时，用户有可能既选了"拒绝，没勾选不再提醒"，又选了"拒绝，且不再提醒"
                        // 当这两种情况都存在时，直接跳转设置页面，让用户赋予权限
                        if (noLongerRemindPermissions.size() > 0) {
                            if (callBackLisenter != null) {
                                callBackLisenter.noLongerRemind(noLongerRemindPermissions.toArray(new String[noLongerRemindPermissions.size()]));
                            }
                        } else if (nextNeedRequestPermissions.size() > 0) {
                            requestPermission(activity, callBackLisenter, nextNeedRequestPermissions.toArray(new String[nextNeedRequestPermissions.size()]));
                        } else {
                            if (callBackLisenter != null) {
                                callBackLisenter.granted();
                            }
                        }
                    }
                });
    }


    public static void goAppDetailSetting(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        context.startActivity(localIntent);
    }

    /**
     * 申请权限后的回调接口
     */
    interface CallBackLisenter {
        void granted();

        void refused();

        void noLongerRemind(String... permissionNames);
    }


}
